#-*- coding: utf-8 -*-

#This file is part of PyAero library.
#
# PyAero is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyAero is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with PyAero.  If not, see <http://www.gnu.org/licenses/>.

__author__ = u'Guillaume Baty'
__copyright__ = u'Copyright 2011-2012 (C) andheo'
__credits__ = [u'Guillaume Baty']
__license__ = "GNU Lesser General Public License"


LEGACY = False

from distutils.command.build import build
from setuptools import setup, find_packages
from sphinx import setup_command
import os
import os.path as osp
import re
import sys

try:
  import bdist_nsi
except ImportError:
  pass

if '--accept-license' in sys.argv :
  sys.argv.remove('--accept-license')
elif sys.platform == 'win32':
  pass # win32 does not support curse used in display_license
else :
  from displicense import display_license
  accepted = display_license()
  if not accepted :
    sys.exit()

# Find version. We have to do this because we can't import it in Python 3 until
# its been automatically converted in the setup process.
def find_version(filename):
  """Thanks to rdflib team (http://code.google.com/p/rdflib/)
  for this small piece of code
  """
  _version_re = re.compile(r'__version__ = "(.*)"')
  for line in open(filename):
    version_match = _version_re.match(line)
    if version_match:
      return version_match.group(1)


def get_package_data(name, extlist):
    """Return data files for package name with extensions in extlist
    Thanks to Pierre Raybaut, Spyder (http://spyderlib.googlecode.com)
    for this small piece of code"""
    flist = []
    # Workaround to replace os.path.relpath (not available until Python 2.6):
    offset = len(name) + len(os.pathsep)
    for dirpath, _dirnames, filenames in os.walk(name):
        for fname in filenames:
            if not fname.startswith('.') and osp.splitext(fname)[1] in extlist:
                flist.append(osp.join(dirpath, fname)[offset:])
    return flist

def get_subpackages(name):
    """Return subpackages of package name.
    Thanks to Pierre Raybaut, Spyder (http://spyderlib.googlecode.com)
    for this small piece of code"""
    splist = []
    for dirpath, _dirnames, _filenames in os.walk(name):
        if osp.isfile(osp.join(dirpath, '__init__.py')):
            splist.append(".".join(dirpath.split(os.sep)))
    return splist

class MyBuild(build):
    """Thanks to Pierre Raybaut, Spyder (http://spyderlib.googlecode.com)
    for this small piece of code"""
    def has_doc(self):
        setup_dir = os.path.dirname(os.path.abspath(__file__))
        return os.path.isdir(os.path.join(setup_dir, 'doc'))
    sub_commands = build.sub_commands + [('build_doc', has_doc)]


class MyBuildDoc(setup_command.BuildDoc):
    """Thanks to Pierre Raybaut, Spyder (http://spyderlib.googlecode.com)
    for this small piece of code"""
    def run(self):
        build = self.get_finalized_command('build')
        sys.path.insert(0, os.path.abspath(build.build_lib))
        dirname = self.distribution.get_command_obj('build').build_purelib
        self.builder_target_dir = osp.join(dirname, 'spyderlib', 'doc')
        try:
            setup_command.BuildDoc.run(self)
        except UnicodeDecodeError:
            print >> sys.stderr, "ERROR: unable to build documentation because Sphinx do not handle source path with non-ASCII characters. Please try to move the source package to another location (path with only ASCII characters)."
        sys.path.pop(0)

cmdclass = {'build': MyBuild, 'build_doc': MyBuildDoc}
nsis_options = {}

excluded = ['doctests', 'tools']
if not LEGACY:
  excluded += ['_pylot.legacy', '_pylot.legacy.*']

packages = find_packages(exclude=excluded)


data_extensions = [
  # Documentation
  '.txt', '.html',
  # Images
  '.png', '.jpg',
  # Databases
  '.xml', '.csv',
  # Qt
  '.ui',
  # i18n
  '.mo', '.ts', '.po',
  ]

version = find_version('pyLot/__init__.py')

setup(
  author='pyLot Team',
  name='pyLot',
  version=version,
  description='pyLot, PyQt based framework',
  url='http://code.google.com/p/pylot/',
  platforms=['any'],
  author_email='guillaume.baty (at) andheo.fr',
  license="GNU LGPLv3",

  include_package_data=True,
  packages=packages,
  package_data={
    '_pylot':get_package_data('_pylot', data_extensions),
    'pyLot_tuto':get_package_data('pyLot_tuto', data_extensions),
    'pyLot_plugins':get_package_data('pyLot_plugins', data_extensions),
    'pyLot_external':get_package_data('pyLot_external', data_extensions)
  },

  requires=['traits(>=4.0.0)', 'apptools(>=4.0.0)', 'envisage(>=4.0.0)',
            'sphinx (>=0.6.0)'],

  scripts=[
    'tools/pyLot-compile-ui-files.py',
    'pyLot_tuto/bin/pyLot-demo-minimal.py',
    'pyLot_tuto/bin/pyLot-demo.py',
    ],

  classifiers=[
    'License :: OSI Approved :: LGPL v3',
    'Operating System :: MacOS',
    'Operating System :: Microsoft :: Windows',
    'Operating System :: OS Independent',
    'Operating System :: POSIX',
    'Operating System :: Unix',
    'Programming Language :: Python :: 2.7',
    'Development Status :: 1 - Planning',
    'Topic :: Scientific/Engineering',
    ],
  cmdclass=cmdclass,
  options={'bdist_nsi': nsis_options}
)

